<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once ('Entity/Relax_Articles_Entity.php');
class Relax_Articles_Model extends Relax_Articles_Entity
{
    public $cate = '';
    public $cid = 0;
    public function __construct()
    {
        parent::__construct();
        $this->lang->load('relax');
    }
    
    public function newCommentBycatetory($cid = 0)
    {
        $sql = "SELECT a.id, a.title, a.alias, a.image, c.fullname, c.contents, 
                rc.title as ctitle, rc.alias as calias
            FROM relax_articles_comments c 
            INNER JOIN relax_articles a ON a.id = c.aid
            INNER JOIN relax_categories rc ON rc.id = a.cid
            WHERE a.`status` = 1 AND c.`status` = 1 AND rc.id = ?
            GROUP BY a.id
            ORDER BY c.created DESC 
            LIMIT 5";
        $query = $this->db->query($sql, array($cid));
        return $query->result();
    }
    
    public function getIdByAlias($alias)
    {
        $sql = "
            SELECT r.id
            FROM relax_articles r 
            WHERE r.alias = ? AND r.`status` = 1
            ";
        $query = $this->db->query($sql, array($alias));
        $obj = $query->row();
        if ($obj) {
            return $obj->id;
        } else {
            return 0;
        }
    }
    
   public function updateHit($id = 0)
   {
        if (!isset($_SESSION['relax_categories'][$id])) {
            $_SESSION['relax_categories'][$id] = $id;
            $sql = "UPDATE relax_articles SET hit = hit + 1 WHERE id = ?";
            $this->db->query($sql, array($id));
        }
   }
    
    public function getArticleById($id)
    {
        $sql = "
            SELECT r.id, r.title, r.alias, r.image, c.title as ctitle, r.summary,
                r.contents, c.alias as calias, c.id as cid 
            FROM relax_articles r 
            INNER JOIN relax_categories c ON r.cid = c.id 
            WHERE r.id = ? AND r.`status` = 1
            ";
        $query = $this->db->query($sql, array($id));
        return $query->row();
    }
    
/**
 * i.	Xem nhiều nhất trong tuần: Liệt kê các bài được xem nhiều nhất trong tuần từ các mục: ĐỐ vui, Truyện cấm cười, wili teghe, truyện tranh cù léc, Thơ lãng xẹt, Ảnh vui
 */
    public function articleByWeek()
    {
        $limit = 10;
        $sql = "SELECT r.id, r.title, r.alias, r.image, c.title as ctitle, c.alias as calias
                FROM relax_articles r
                INNER JOIN relax_categories c ON r.cid = c.id
                WHERE YEARWEEK(FROM_UNIXTIME(r.created, '%Y-%m-%d'))  = YEARWEEK(CURRENT_DATE) 
                    AND r.status = 1
                ORDER BY r.hit DESC, r.created DESC
                LIMIT $limit";
        $query = $this->db->query($sql);
        return $query->result();
    }
    
/**
 * ii.	Đố vui: Liệt kê 5 bài mới nhất và 10 xem nhiều nhất ....
 */    
    public function articleByCatetory($cid, $ord = 1)
    {
        $sql = "SELECT r.id, r.title, r.alias, r.image, r.summary, c.title as ctitle, c.alias as calias
            FROM relax_articles r
            INNER JOIN relax_categories c ON r.cid = c.id
            WHERE r.cid =  ? AND r.status = 1 ";
        if ($ord == 1) {
           $sql .= " ORDER BY r.hit DESC " ;
        } elseif ($ord == 2) {
            $sql .= " ORDER BY r.created DESC " ;
        }
        $sql .= " LIMIT 10 ";
        $query = $this->db->query($sql, array($cid));
        return $query->result();
    }

    
/**
 * Top 1 by catetory
 */
    public function top1($cid)
    {
        $sql = "SELECT r.id, r.title, r.alias, r.image, r.summary, c.title as ctitle, c.alias as calias
            FROM relax_articles r
            INNER JOIN relax_categories c ON r.cid = c.id
            WHERE r.cid =  ? AND r.status = 1 ";
        $sql .= " ORDER BY r.created DESC " ;
        $sql .= " LIMIT 1 ";
        $query = $this->db->query($sql, array($cid));
        return $query->row();
    }
    public function CountArticleByCatetory($cid)
    {
        $sql = "SELECT r.id
            FROM relax_articles r
            INNER JOIN relax_categories c ON r.cid = c.id
            WHERE r.cid =  ? AND r.status = 1 ";
        $query = $this->db->query($sql, array($cid));
        return $query->num_rows();
    }
    public function getArticleByCatetory($cid, $offset = 1, $limit = 10)
    {
        $sql = "SELECT r.id, r.title, r.alias, r.image, r.summary, c.title as ctitle, c.alias as calias
            FROM relax_articles r
            INNER JOIN relax_categories c ON r.cid = c.id
            WHERE r.cid =  ? AND r.status = 1 ";
        $sql .= " ORDER BY r.created DESC " ;
        $sql .= " LIMIT $offset, $limit ";
        $query = $this->db->query($sql, array($cid));
        return $query->result();
    }
    public function getTopHitArticleByCatetory($cid)
    {
        $limit = 10;
        $sql = "SELECT r.id, r.title, r.alias, r.image, c.title as ctitle, c.alias as calias
                FROM relax_articles r
                INNER JOIN relax_categories c ON r.cid = c.id
                WHERE r.cid =  ? AND r.status = 1 AND FROM_UNIXTIME(r.created, '%Y-%m-%d') >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
                ORDER BY r.hit DESC, r.created DESC
                LIMIT $limit";
        $query = $this->db->query($sql, array($cid));
        return $query->result();
    }
    // menu top
    public function getCategoryName($cid)
    {
        $this->load->model('relax_categories_model');
        $relax = new Relax_Categories_Model();
        $obj = $relax->getRelax_CategoriesById($cid);
        return $obj->title;
    }
    

    public function dataSort($field, $order)
    {
        $xOrder = $order == 'asc' ? 'desc' : 'asc';
        $img = $order == 'desc' ? '<img src=\'/data/admin/down.jpg\' />' : ' <img src=\'/data/admin/up.jpg\' />';
        $url = anchor($this->cate.'/sort/' . $field . '/' . $xOrder, t($field) . $img);
        $_SESSION['sm_sort_'.$this->cate] = array(
            'field' => $field,
            'order' => $order,
            'url' => $url);
    }

    public function dataIndex($target)
    {
        $numshow = 25;
        $this->db->select('relax_articles.id, relax_articles.title, relax_articles.created, relax_articles.status, relax_articles.hit, relax_categories.title as cid_type');
        $this->db->from('relax_articles');

        $this->db->join('relax_categories', 'relax_articles.cid = relax_categories.id');

        //if ($this->session->userdata('sm_filter_relax_categories'))
        $this->db->where('relax_articles.cid', $this->cid);
        
        if ($this->session->userdata('sm_find_relax_articles')) {
            $this->db->like('relax_articles.title', $this->session->userdata('sm_find_relax_articles'));
        }
        if (isset($_SESSION['sm_sort_'.$this->cate])) {
            $sort = $_SESSION['sm_sort_'.$this->cate];
            $this->db->order_by('relax_articles.' . $sort['field'], $sort['order']);
        } else {
            $this->db->order_by('relax_articles.created', 'desc');
        }
        $this->db->limit($numshow, $target);
        $query = $this->db->get();
        $paging = paging_admin('relax_articles/index', $this->_total(), $numshow, 4);
        return array(
            'query' => $query,
            'paging' => $paging,
            'cate' => $this->cate,
            'fil_relax_categories' => $this->Filter_relax_categories(),
            'formFind' => $this->formFind());
    }

    private function cbo_relax_categories($id = 0)
    {
        $this->load->helper("form");
        $query = $this->db->get("relax_categories");
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $sl = $id == 0 ? set_value("cid") : $id;
        return form_dropdown("cid", $options, $sl);
    }

    private function _total()
    {
        return $this->db->count_all_results("relax_articles");
    }

    private function _checkrelax_articlesById($id)
    {
        $query = $this->db->get_where("relax_articles", array("id" => $id));
        if ($query->num_rows() > 0)
            return true;
        else {
            notify_set_messages(notify_atten(t("Record không tồn tại")), "relax_articles");
            return false;
        }
    }

    private function formFind()
    {
        $this->load->helper('form');
        $attributes = array('name' => 'frmFind', 'id' => 'frmFind');
        $cate = $this->cate;
        $f = form_open(site_url($cate.'/find'), $attributes);
        $data = array(
            'name' => 'txt_find',
            'id' => 'txt_find',
            'value' => '',
            'style' => 'width:200px');
        $f .= form_input($data);
        $s = array(
            'name' => 'submit',
            'value' => t('Find'),
            'class' => 'ibutton green',
            'style' => 'margin-left:10px');
        $f .= form_submit($s);
        if ($this->session->userdata('sm_find_relax_articles')) {
            $r = array(
                'name' => 'btnReset',
                'value' => 'Reset',
                'class' => 'ibutton red',
                'style' => 'margin-left:10px');
            $f .= form_submit($r);
        }
        $f .= form_close();
        return $f;
    }

    private function Filter_relax_categories()
    {
        $this->load->helper('form');
        $query = $this->db->get('relax_categories');
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $id = !$this->session->userdata('sm_filter_relax_categories') ? 0 : $this->session->userdata('sm_filter_relax_categories');
        $attributes = array('name' => 'frmFilterrelax_categories', 'id' => 'frmFilterrelax_categories');
        $f = form_open(site_url('relax_articles/filterrelax_categories'), $attributes);
        $f .= form_dropdown('cid', $options, $id);
        $data = array(
            'name' => 'btnFilterrelax_categories',
            'class' => 'ibutton green',
            'style' => 'margin-left:10px',
            'value' => t('Filter'));
        $f .= form_submit($data);
        if ($this->session->userdata('sm_filter_relax_categories')) {
            $r = array(
                'name' => 'btnReset',
                'class' => 'ibutton red',
                'style' => 'margin-left:10px',
                'value' => 'Reset');
            $f .= form_submit($r);
        }
        $f .= form_close();
        return $f;
    }


    public function dataEdit($id)
    {
        if (!$this->_checkrelax_articlesById($id))
            return redirect(site_url('relax_articles'));
        $this->load->helper('editor');
        $query = $this->db->get_where('relax_articles', array('id' => $id));
        return array(
            'query' => $query, 
            'cbo_relax_categories' => $this->cbo_relax_categories($query->row('cid')),
            'cate' => $this->cate,
            'cid' => $this->cid
            );
    }

    public function dataAdd()
    {
        $this->load->helper('editor');
        return array(
            'cbo_relax_categories' => $this->cbo_relax_categories(),
            'cate' => $this->cate,
            'cid' => $this->cid
            );
    }

    public function checkForm()
    {
        $this->form_validation->set_rules('title', t('title'), 'trim|required');
        $this->form_validation->set_rules('image', t('image'), 'trim|required');
        $this->form_validation->set_rules('summary', t('summary'), 'trim|required');
        $this->form_validation->set_rules('contents', t('contents'), 'trim|required');
        $this->form_validation->set_rules('created', t('created'), 'trim|required');
        $this->form_validation->set_rules('status', t('status'), 'trim');
        $this->form_validation->set_rules('keyword', t('keyword'), 'trim');
        $this->form_validation->set_rules('description', t('description'), 'trim');
        //$this->form_validation->set_rules('cid', t('cid'), 'trim|required|integer');
        return $this->form_validation->run();
    }

    public function doUpdate()
    {
        $this->load->helper('text');
        $title = $this->input->post('title');
        $time = strtotime($this->input->post('created'));
        $this->setTitle($title);
        $this->setAlias(iurl_title($title).'-'.date('y-m-d', $time));
        $this->setImage($this->input->post('image'));
        $this->setSummary($this->input->post('summary'));
        $this->setContents($this->input->post('contents'));
        $this->setCreated($time);
        $this->setStatus($this->input->post('status'));
        $this->setKeyword($this->input->post('keyword'));
        $this->setDescription($this->input->post('description'));
        $this->setCid($this->input->post('cid'));

        if (isset($_POST['idx'])) {
            $id = decrypt($_POST['idx']);
            $this->setId($id);
            $this->setChanged(time());
        } 
        return $this->save();
    }
}
